<!--
  @Description:新增编辑品类
  @Author:zqy
  @Date:2022-12-16 15:05:32
  @Last Modified by:zqy
  @Last Modified time:2022-12-16 15:05:32
-->
<template>
  <el-dialog
    ref="formDlg"
    :title="`${!!(detail && detail.id)?'编辑':'新增'}品类`"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="500px"
    @close="closeDialog"
  >
    <div style="padding-right:30px">
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
        <el-row>
          <el-col v-if="detail && detail.parentId" :span="24">
            <el-form-item label="父级品类:">
              {{ detail.parentName }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品品类:" prop="categoryId">
              <el-cascader
                v-model="formData.categoryId"
                placeholder="请选择类目"
                :options="categoryTreeList"
                :props="{
                  checkStrictly: false,
                  multiple:false,
                  emitPath:false,
                  value:'categoryId',
                  label:'categoryName',
                  children:'childList'
                }"
                style="width:100%"
                size="mini"
                :disabled="!!(detail && detail.id)"
                filterable
                clearable
                collapse-tags
                @change="handleCategoryChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="品类编码:" prop="code">
              <el-input v-model.trim="formData.code" maxlength="20" :disabled="!!(detail && detail.id)" show-word-limit placeholder="请输入编码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="品类名称:" prop="name">
              <el-input v-model.trim="formData.name" maxlength="25" show-word-limit placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属空间:" prop="spaceConfId">
              <QupSearchSelectPicker
                :url="styleApi"
                placeholder="请选择空间"
                lable-name="name"
                value-name="id"
                custom-name="name"
                method="post"
                :value.sync="formData.spaceConfId"
                :lable.sync="formData.spaceConfName"
                :params="{query:{enableFlag:{value:1,operator:'='}},type:0}"
                filterable
                remote
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传封面:" prop="picUrl">
              <div class="img-upload-container">
                <qup-img-uploader
                  :width="100"
                  :height="100"
                  mask
                  :image-url="cateImage.absoluteUrl"
                  :relative-url="cateImage.relativeUrl"
                  @upload-success="handleUploadSuccess"
                  @remove="handleDelImg"
                />
                <div class="icon-msg">建议图片尺寸大小90*90,不超过1M,支持png\jpg\jpeg</div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button v-loading="submiting" size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveConfig } from '@/api/categoryConf'
import QupImgUploader from '@/components/imgUploader'
export default {
  name: 'CategoryEdit',
  components: { QupImgUploader },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    categoryTreeList: {
      type: Array,
      default: () => []
    },
    detail: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      styleApi: `${process.env.VUE_APP_BASE_API}/api/v1/v2SpaceConf/page`,
      formData: {
        id: null,
        categoryId: '',
        code: '',
        name: '',
        spaceConfId: '',
        spaceConfName: '',
        picUrl: '',
        parentId: '',
        enableFlag: 1
      },
      formRules: {
        categoryId: [
          { required: true, message: '请选择商品品类', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入品类编码', trigger: 'blur' },
          { pattern: /^[a-zA-Z\d][\w-]{0,19}$/, message: '输入字母、数字、中划线、下划线' }
        ],
        name: [
          { required: true, message: '请输入品类名称', trigger: 'blur' }
        ],
        spaceConfId: [
          { required: true, message: '请选择风格', trigger: 'blur' }
        ],
        picUrl: [
          { required: true, message: '请上传封面图', trigger: 'change' }
        ]
      },
      cateImage: {
        absoluteUrl: '',
        relativeUrl: ''
      },
      submiting: false
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    lastCategoryList() {
      // 所有末级类目
      const list = this.getCategoryLastNode(this.categoryTreeList)
      return list
    }
  },
  created() {
    if (this.detail && this.detail.id) {
      const data = this.detail
      const enableFlag = [0, '0', 1, '1'].includes(data.enableFlag) ? data.enableFlag : 1
      this.formData = {
        id: data.id,
        parentId: data.parentId || '',
        categoryId: data.categoryId,
        code: data.code,
        name: data.name,
        spaceConfId: data.spaceConfId,
        spaceConfName: data.spaceConfName,
        picUrl: data.picUrl,
        enableFlag
      }
      this.cateImage = {
        absoluteUrl: this.formatImageUrl(data.picUrl),
        relativeUrl: data.picUrl
      }
    }
    if (this.detail && this.detail.parentId) {
      this.$set(this.formData, 'parentId', this.detail.parentId)
    }
  },

  methods: {
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {
        id: null,
        parentId: '',
        categoryId: '',
        code: '',
        name: '',
        spaceConfId: '',
        spaceConfName: '',
        picUrl: '',
        enableFlag: 1
      }
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    submitForm(type) {
      if (this.submiting) return
      this.$refs['refForm'].validate(async(valid) => {
        if (valid) {
          const formData = Object.assign(this.formData)
          if (!formData.parentId) {
            delete formData.parentId
          }
          this.submiting = true
          await saveConfig(formData).then(res => {
            this.submiting = false
            if (res.success === 1) {
              this.$message({
                // message: res.msg ? res.msg : `${formData.id ? '编辑' : '新增'}保存成功`,
                message: `${formData.id ? '编辑' : '新增'}保存成功`,
                type: 'success'
              })
              this.$emit('success', !formData.id)
              this.closeDialog()
            }
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    },
    // 获取树形类目的所有末级类目
    getCategoryLastNode(data) {
      const result = []
      data.forEach(item => { // 遍历树
        const loop = data => {
          const child = data.childList
          if (child && child.length) { // 是否有子节点，有则继续遍历下一级，无则是叶子节点
            for (let i = 0; i < child.length; i++) {
              loop(child[i])
            }
          } else {
            result.push(data)
          }
        }
        loop(item)
      })
      return result
    },
    // 品类选择变更 el-cascader 为false时
    handleCategoryChange(id) {
      const node = this.lastCategoryList.find(v => v.categoryId === id)
      this.$set(this.formData, 'name', (node && node.categoryName) || '')
    },
    handleUploadSuccess(res, file, fileList) {
      this.formData.picUrl = res.storeFileName
      this.cateImage = {
        absoluteUrl: res.url,
        relativeUrl: res.storeFileName
      }
    },
    handleDelImg() {
      this.formData.picUrl = ''
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
    }
  }
}
</script>
<style lang='scss' scoped>
  .img-upload-container {
    .icon-msg{
      margin-top: 10px;
      color: #999;
    }
  }
</style>
